package com.eleventwelve.iris.web.validator;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.opentides.bean.BaseReportValidator;
import org.opentides.bean.DynamicReport;
import org.opentides.util.StringUtil;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.Errors;

public class ReportValidator implements BaseReportValidator {

	@SuppressWarnings("rawtypes")
	@Override
	public boolean supports(Class clazz) {
		return DynamicReport.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object arg0, Errors arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public List<String> validate(HttpServletRequest request) {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		Locale locale = LocaleContextHolder.getLocale();

		List<String> errorMessages = new ArrayList<String>();
		String endDate = request.getParameter("endDate");
		String startDate = request.getParameter("startDate");

		if (startDate != null && StringUtil.isEmpty(startDate)) {
			errorMessages.add(messageSource.getMessage("error.required-short",
					new Object[] { "Start Date" }, "Start Date is required.",
					locale));
		}
		
		if (endDate != null && StringUtil.isEmpty(endDate)) {
			errorMessages.add(messageSource.getMessage("error.required-short",
					new Object[] { "End Date" }, "End Date is required.",
					locale));
		}
		
		if (startDate != null && endDate != null
				&& !StringUtil.isEmpty(startDate)
				&& !StringUtil.isEmpty(endDate)) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");
			try {
				Date start = dateFormat.parse(startDate);
				Date end = dateFormat.parse(endDate);
				if (end.before(start)) {
					errorMessages.add(messageSource.getMessage(
							"error.must-be-after", new Object[] { "End Date",
									"Start date" },
							"End Date must be after Start Date", locale));
				}
			} catch (Exception e) {
				errorMessages.add(messageSource.getMessage(
						"error.invalid-entered-data",
						new Object[] { "Start/End Date" },
						"Invalid entered Start/End date.", locale));
			}
		}

		if (errorMessages.size() > 0) {
			return errorMessages;
		} else {
			return null;
		}
	}

}
